﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using Config;
using System.Diagnostics;
using System.Collections;
namespace SerialportSample
{

    public partial class SerialportSampleForm : Form
    {
        #region 串口

        #endregion
        //public enum MODE { SS,RR,RRHC,UH};
        private string mode = "SS";
        Form ConfigForm = new Form();
        private  string file1 = "test.txt";
        private  string file2 = "out.txt";
        private bool start = false;
        private long timego = 0;
        public SerialportSampleForm()//构造函数
        {
            InitializeComponent();
            //初始化下拉串口名称列表框
            //获取当前计算机串口的名称数组
            //this.skinEngine1.SkinFile = "DeepGreen.ssk";//导入皮肤
            /*开启线程*/
            //this.bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bwDoWork);
           // this.bw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            initChart();
            initTimer2();
            textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);  
        }
        public void initTimer2()
        {
            this.timer2.Interval = 1000;
            this.timer2.Tick += new System.EventHandler(this.time2_Tick);
            this.timer2.Start();
        }
        private void time2_Tick(object sender, EventArgs e)
        {
            this.label5.Text = DateTime.Now.ToString();
           
            if (start)
            { 
                timego++;
                button3.Text = "#" + timego + "秒";
            }
            if (start && (timego % 10 == 0))
            {
                bool isHavePro = false;
                System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    if ("LMTPro" == myProcess.ProcessName)
                    {
                        isHavePro = true;
                        break;//强制关闭该程序
                    }
                }
                if (!isHavePro) {
                    timego = 0;
                    start = false;
                    ProgressBar1.Style = ProgressBarStyle.Blocks;
                    button3.Enabled = true;
                    button4.Enabled = false;
                    button3.Text = "数据处理";
                    textBox1.Enabled = true;
                }
            }
        }
        //增加图标
        private class IconIndexes
        {
            public const int MyComputer = 0;      //我的电脑
            public const int ClosedFolder = 1;    //文件夹关闭
            public const int OpenFolder = 2;      //文件夹打开
            public const int FixedDrive = 3;      //磁盘盘符
            public const int MyDocuments = 4;     //我的文档
        }

        public void initChart()
        {
            //chart2.Series[0].Points.AddXY(1, 0); 
        }
        void bwDoWork1(object sender, DoWorkEventArgs e)
        {

            this.bw.ReportProgress(0, "正在读取数据文件");
            //StreamReader sr = new StreamReader(new FileStream("test.txt ", FileMode.Open, FileAccess.Read));
            int k;
            string s;
            int len;
            for (int i = 0; i < 100; ++i)
            {
                this.bw.ReportProgress(i, "运行中!");
                /*
                this.Invoke((MethodInvoker)delegate
                {
                    this.toolStripProgressBar1.Value += this.toolStripProgressBar1.Step;
                });
                 * */
                System.Threading.Thread.Sleep(100);

            }
            this.bw.ReportProgress(100, "Complete!");
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBar1.Value = e.ProgressPercentage;
            // toolStripProgressBar1.Text = e.UserState as String;
            toolStripStatusLabel1.Text = e.UserState as String;
        }

        private void SerialportSampleForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            //在关闭窗体前发生，此时可以取消窗体的关闭。
            DialogResult result = MessageBox.Show("你确定关闭吗", "提示",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                e.Cancel = false;  //点击OK    

                //关闭LMTPro
                System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
                foreach (System.Diagnostics.Process myProcess in myProcesses)
                {
                    if (("LMTPro" == myProcess.ProcessName) || ("MTSHOAW" == myProcess.ProcessName))
                        myProcess.Kill();//强制关闭该程序
                }
                //关闭LMTPro
                System.Diagnostics.Process.GetCurrentProcess().Kill();
                //System.Environment.Exit(System.Environment.ExitCode);
                this.Dispose();
                this.Close();
            }
            else
            {
                e.Cancel = true;
            }

        }

        private void 配置信息修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {             
                StreamReader sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                String line;
                try
                {
                    sr.ReadLine();
                    line = sr.ReadLine();//out.t76
                    sr.Close();
                    if (line == null || line == "")
                    {
                        MessageBox.Show("配置文件错误"); return;
                    }
                    filenameSiteInfo = SelectPath + "\\" + line + ".info";
                    System.Diagnostics.Process.Start("notepad.exe", filenameSiteInfo);
                }
                catch (Exception ex)
                {
                    sr.Close();
                    MessageBox.Show("配置文件错误");
                }
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }

        }

        private void 配置文件查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //相对路径
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {
                Config.ConfigForm config = new Config.ConfigForm(SelectPath);

                config.selectpathconfig = SelectPath;
                config.ShowDialog();
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
              string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {             
                StreamReader sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                String stationName;
                try
                {
                    sr.ReadLine();
                    stationName = sr.ReadLine();//out.t76
                    if (stationName == null || stationName == "")
                    {
                        MessageBox.Show("配置文件错误"); return;
                    }
                     sr.ReadLine(); sr.ReadLine();
                     sr.ReadLine(); sr.ReadLine();
                     sr.ReadLine();
                     string remoteStationName = sr.ReadLine();
                     sr.Close();
                    string fileName="111";
                    if(mode == "SS") fileName = stationName+"_SS.dat";
                    else if(mode == "RR") fileName = stationName+"vs"+remoteStationName+"_RR.dat";
                    else if(mode == "RRHC") fileName = stationName+"vs"+remoteStationName+"_RRHC.dat";
                    else if(mode == "UH") fileName = stationName+"vs"+remoteStationName+"_UH.dat";
                    filenameSiteInfo = SelectPath + "\\result\\" + fileName;
                    //MessageBox.Show(filenameSiteInfo);
                    if (!File.Exists(filenameSiteInfo))
                    {
                        MessageBox.Show("测深文件不存在，请在左侧选中目录或下方手动输入后确定" + filenameSiteInfo);
                        return;
                    }
                    OutForm f2 = new OutForm(this, filenameSiteInfo);
                    f2.ShowDialog();
                }
                catch (Exception ex)
                {
                    sr.Close();
                    MessageBox.Show("配置文件错误");
                }
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }
            /*
            string fileName = ;
            string filenameSiteInfo = SelectPath + "\\" + "result\\SiteInfo.dat";
            string filenameoutt76 = getoutFileName(filenameSiteInfo);*/
          
        }

        private void buttonOpenClose_Click(object sender, EventArgs e)
        {
            bw.RunWorkerAsync();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {
                StreamReader sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                String line;
                try
                {
                    sr.ReadLine();
                    line = sr.ReadLine();//out.t76 
                    sr.Close();
                    if (line == null || line == "")
                    {
                        MessageBox.Show("配置文件错误"); return;
                    }
                    string stationName = line + ".info";
                    filenameSiteInfo = SelectPath + "\\" + stationName;
                    sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                    if (File.Exists(filenameSiteInfo))
                    {
                        sr.ReadLine();
                        sr.ReadLine();
                        sr.ReadLine();
                        line = sr.ReadLine();//out.t76
                        sr.Close();
                    }
                    else
                    {
                        sr.Close();
                        MessageBox.Show("配置文件错误" + filenameSiteInfo); return;
                    }                  
                    filenameSiteInfo = SelectPath + "\\" + line;

                    if (!File.Exists(filenameSiteInfo))
                    {
                        MessageBox.Show("时间序列文件不存在，请在左侧选中目录或下方手动输入后回车" + filenameSiteInfo);
                        return;
                    }
                    WaveForm f2 = new WaveForm(this, filenameSiteInfo);

                    f2.ShowDialog();

                }
                catch (Exception ex)
                {
                    sr.Close();
                    MessageBox.Show("配置文件错误");
                }
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }         
        }
        private void userInputPath(string path)
        {
            this.listView1.Items.Clear();
            //数据更新 UI暂时挂起直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度  
            this.listView1.BeginUpdate();
            //实例目录与子目录  
            DirectoryInfo dir = new DirectoryInfo(path);
            //获取当前目录文件列表  

            SelectPath = path;
            textBox1.Text = SelectPath;//文件路径
            try
            {
                FileInfo[] fileInfo = dir.GetFiles();//此处有点问题，需要判断文件只能读
                //循环输出获取文件信息  
                for (int i = 0; i < fileInfo.Length; i++)
                {
                    ListViewItem listItem = new ListViewItem();
                    //listItem.SubItems[0].Text = fileInfo[i].Name;             //文件名(方法二)  
                    listItem.Text = fileInfo[i].Name;    //显示文件名  
                    listItem.ForeColor = Color.Blue;                            //设置行颜色  

                    //length/1024转换为KB字节数整数值 Ceiling返回最小整数值 Divide除法  
                    long length = fileInfo[i].Length;                                //获取当前文件大小  
                    listItem.SubItems.Add(Math.Ceiling(decimal.Divide(length, 1024)) + " KB");

                    //获取文件最后访问时间  
                    //listItem.SubItems.Add(fileInfo[i].LastWriteTime.ToString());  

                    //获取文件扩展名时可用Substring除去点 否则显示".txt文件"  
                    listItem.SubItems.Add(fileInfo[i].Extension + "文件");
                    //加载数据至listview  
                    this.listView1.Items.Add(listItem);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("选择的路径不能为盘根目录，且具有读写权限", "错误", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
            }
            //结束数据处理,UI界面一次性绘制 否则可能出现闪动情况  
            this.listView1.EndUpdate();
        }
        private void SerialportSampleForm_Load(object sender, EventArgs e)
        {

            button3.Enabled = true;//Btn3按钮可以按
            button4.Enabled = false;//Btn4按钮不可以

            //toolStripStatusLabel1.Text = "系统当前时间：" + System.DateTime.Now.ToString();//设置StatusStrip控件时间

            //TreeView添加树
            TreeNode RootNode = new TreeNode("我的电脑");//实例化TreeNode类 
            RootNode.Tag = "我的电脑";   //树节点数据
            RootNode.Text = "我的电脑"; //树节点标签内容  
            this.treeView1.Nodes.Add(RootNode);//树中添加根目录  

            var myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            TreeNode DocNode = new TreeNode(myDocuments);
            DocNode.Tag = "我的文档";                            //设置结点名称  
            DocNode.Text = "我的文档";
            DocNode.ImageIndex = IconIndexes.MyDocuments;         //设置获取结点显示图片  
            DocNode.SelectedImageIndex = IconIndexes.MyDocuments; //设置选择显示图片  
            RootNode.Nodes.Add(DocNode);                          //rootNode目录下加载节点  
            DocNode.Nodes.Add("");

            //循环遍历计算机所有逻辑驱动器名称(盘符)
            foreach (string drive in Environment.GetLogicalDrives())
            { //实例化DriveInfo对象 命名空间System.IO 
                var dir = new DriveInfo(drive);
                switch (dir.DriveType)//判断驱动器类型 
                {
                    case DriveType.Fixed: //仅取固定磁盘盘符fixed
                        {

                            TreeNode tNode = new TreeNode(dir.Name);//Split仅获取盘符字母 
                            tNode.Name = dir.Name;
                            tNode.Tag = tNode.Name;
                            tNode.ImageIndex = IconIndexes.ClosedFolder;         //获取结点显示图片  
                            tNode.SelectedImageIndex = IconIndexes.OpenFolder;//选择显示图片

                            treeView1.Nodes.Add(tNode);//加载驱动节点
                            tNode.Nodes.Add("");//展开
                        }
                        break;
                }

            }
            RootNode.Expand();//展开树状视图 

            //调用SetListView()函数初始化设置ListView 
            SetListView();

        }

        /// <summary>
        /// 自定义类TreeViewItems 调用其Add(TreeNode e)方法加载子目录 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static class TreeViewItems
        {
            public static void Add(TreeNode e)
            {
                try
                {
                    if (e.Tag.ToString() != "我的电脑")
                    {
                        e.Nodes.Clear();//清除空节点再加载子节点
                        TreeNode tNode = e; //获取选中\展开\折叠结点  
                        string path = tNode.Name; //路径  

                        if (e.Tag.ToString() == "我的文档")
                        {
                            path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        }



                        //获取指定目录中的子目录名称并加载结点
                        string[] dics = Directory.GetDirectories(path);
                        foreach (string dic in dics)
                        {
                            TreeNode SubNode = new TreeNode(new DirectoryInfo(dic).Name);//实例化完整目录
                            SubNode.Name = new DirectoryInfo(dic).FullName;

                            SubNode.Tag = SubNode.Name;

                            SubNode.ImageIndex = IconIndexes.ClosedFolder;   //获取节点显示图片  
                            SubNode.SelectedImageIndex = IconIndexes.OpenFolder; //选择节点显示图片 

                            tNode.Nodes.Add(SubNode);
                            SubNode.Nodes.Add("");//加载空节点 实现+号 
                        }
                    }

                }
                catch (Exception msg)
                {
                    MessageBox.Show("读取文件错误");
                }
            }
        }
        /// <summary>  
        /// 自定义函数设置ListView控件初始属性  
        /// </summary> 
        private void SetListView()
        {
            this.listView1.GridLines = true;//行和列是否显示网格线
            this.listView1.View = View.Details;//显示方式(注意View是Details详细显示)  
            this.listView1.LabelEdit = false;//是否可编辑 
            this.listView1.Scrollable = true; //没有足够的空间显示时,是否添加滚动条
            this.listView1.HeaderStyle = ColumnHeaderStyle.Clickable; //对表头进行设置  
            this.listView1.FullRowSelect = true;
            //设置listView列标题头 宽度为9/13 2/13 2/13
            this.listView1.Columns.Add("名称", 9 * listView1.Width / 13);
            this.listView1.Columns.Add("大小", 2 * listView1.Width / 13);
            this.listView1.Columns.Add("类型", 2 * listView1.Width / 13);

        }





        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {

            e.Node.Expand();
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeViewItems.Add(e.Node);

        }
        // 获取选中文件夹路径名称
        public string SelectPath = "";//定义TreeView选中文件夹路径
        private string GetPathFromNode(TreeNode node)
        {
            //注意:树形控件中我只赋值Tag\Name,使用Text时赋值即可使用  
            if (node.Parent == null)
            {
                return node.Name;
            }
            //Path.Combine组合产生路径 如 Path.Combine("A","B")则生成"A\\B"  
            return Path.Combine(GetPathFromNode(node.Parent), node.Name);
        }

        /*
        public string getoutFileName(string path)
        {
            StreamReader sr = null; 

            try
            {
                sr = new StreamReader(path, System.Text.Encoding.Default);
                String line;
                sr.ReadLine();
                line = sr.ReadLine();//out.t76
                sr.Close();
                file1 = line;
                file2 = file1 + ".dat";
                return line;
            }
            catch (Exception ex)
            {
                if(sr!=null)sr.Close();
                return null;             
            }
            if (sr != null) sr.Close();
            return null;
        }
       
        public string getoutFileName()
        {
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            string filenameoutt76 = getoutFileName(filenameSiteInfo);

            if (filenameoutt76 == null)
            {
                return null;
            }
            return filenameoutt76;
        } */

        //CMD调用程序
        public void button3_Click(object sender, EventArgs e)
        {
           // this.bw.ReportProgress(0, "正在读取数据文件...");
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            string filenameoutt76 = "111";
            if (File.Exists(filenameSiteInfo))
            {
                StreamReader sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                String line;
                try
                {
                    sr.ReadLine();
                    line = sr.ReadLine();//out.t76 
                    sr.Close();
                    if (line == null || line == "")
                    {                    
                        MessageBox.Show("配置文件内容错误" + filenameSiteInfo); return;
                    }
                    string stationName = line + ".info";
                    filenameSiteInfo = SelectPath + "\\" + stationName;
                    sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                    if (File.Exists(filenameSiteInfo))
                    {
                        sr.ReadLine();
                        sr.ReadLine();
                        sr.ReadLine();
                        filenameoutt76 = sr.ReadLine();//out.t76
                        sr.Close();
                    }
                    else
                    {
                        sr.Close();
                        MessageBox.Show("配置文件错误" + filenameSiteInfo); return;
                    }                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show("配置文件错误" + filenameSiteInfo);
                }
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件"); return;
            }


            
            if (filenameoutt76 == null)
            {
                MessageBox.Show("配置文件不存在或者格式错误，请检查" + filenameSiteInfo); return;
            }
            filenameoutt76 = SelectPath + "\\" + filenameoutt76;
            //MessageBox.Show(filenameoutt76); 
            //string filenameoutt76 = SelectPath + "\\" + "out.t76";
            //判断是否选中"LMTPro.exe文件
            if (SelectName == "LMTPro.exe")
            {
                if (File.Exists(filenameSiteInfo) && File.Exists(filenameoutt76))//判断选中文件夹中是否含有SiteInfo.dat文件与out.t76文件
                {

                    //cmd
                    Process p = new Process();//新进程
                    p.StartInfo.FileName = "cmd.exe";//打开cmd程序
                    p.StartInfo.UseShellExecute = false;//不使用shell启动程序
                    p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动 
                    p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息 
                    p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息 
                    p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出 
                    p.StartInfo.CreateNoWindow = true;//true表示不显示黑框，false表示显示dos界面


                    try
                    {
                        //进度条
                        /*
                        ProgressBar1.Value = 0;
                        ProgressBar1.Minimum = 0;
                        ProgressBar1.Maximum = 100;
                        ProgressBar1.Step = 1;
                         * */
                        ProgressBar1.Style = ProgressBarStyle.Marquee;
                        //timer1.Enabled = true;



                        //运行LMTPro
                        p.Start();
                        p.StandardInput.WriteLine("cd /d " + SelectPath);
                        p.StandardInput.WriteLine(SelectName);
                        p.StandardInput.WriteLine("exit");//退出
                        p.Close();//关闭

                        button3.Enabled = false;
                        button4.Enabled = true;
                        textBox1.Enabled = false;
                        //this.bw.ReportProgress(10, "算法处理中...");
                        start = true;

                    }
                    catch (Exception msg)
                    {
                        MessageBox.Show(msg.Message);
                    }


                }
                else if (File.Exists(filenameSiteInfo) && File.Exists(filenameoutt76) == false)
                {
                    MessageBox.Show("LMTPro.exe文件缺少"+filenameoutt76+"文件，无法运行");
                }
                else if (File.Exists(filenameSiteInfo) == false && File.Exists(filenameoutt76))
                {
                    MessageBox.Show("LMTPro.exe文件缺少SiteInfo.dat文件，无法运行");
                }
                else if (File.Exists(filenameSiteInfo) == false && File.Exists(filenameoutt76) == false)
                {
                    MessageBox.Show("LMTPro.exe文件缺少SiteInfo.dat文件与" + filenameoutt76 + "文件，无法运行");
                }


            }
            else
            {
                MessageBox.Show("请选中LMTPro.exe文件。具体方法：请在左侧选中目录或下方手动输入目录后回车");
            }

        }



        public string SelectName;//将选中文件名赋值给全局变量
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            ListView li = new ListView();
            string str = listView1.SelectedItems[0].Text;
            SelectName = str;//获取文件名
            textBox1.Text = SelectPath + "\\" + SelectName;



        }



        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //try
            //{
            //定义变量  
            long length;                        //文件大小  
            string path;                        //文件路径  
            TreeNode clickedNode = e.Node;      //获取当前选中结点  

            //移除ListView所有项   
            this.listView1.Items.Clear();
            //获取路径赋值path                
            if (clickedNode.Tag.ToString() == "我的文档")
            {
                //获取计算机我的文档文件夹  
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }
            else
            {
                //通过自定义函数GetPathFromNode获取结点路径  
                path = GetPathFromNode(clickedNode);
            }

            //由于"我的电脑"为空结点,无需处理,否则会出现路径获取错误或没有找到"我的电脑"路径  
            if (clickedNode.Tag.ToString() != "我的电脑")
            {
                //数据更新 UI暂时挂起直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度  
                this.listView1.BeginUpdate();
                //实例目录与子目录  
                DirectoryInfo dir = new DirectoryInfo(path);
                //获取当前目录文件列表  

                SelectPath = path;
                textBox1.Text = SelectPath;//文件路径
                try
                {
                    FileInfo[] fileInfo = dir.GetFiles();//此处有点问题，需要判断文件只能读
                                                         //循环输出获取文件信息  
                    for (int i = 0; i < fileInfo.Length; i++)
                    {
                        ListViewItem listItem = new ListViewItem();
                        //listItem.SubItems[0].Text = fileInfo[i].Name;             //文件名(方法二)  
                        listItem.Text = fileInfo[i].Name;    //显示文件名  
                        listItem.ForeColor = Color.Blue;                            //设置行颜色  

                        //length/1024转换为KB字节数整数值 Ceiling返回最小整数值 Divide除法  
                        length = fileInfo[i].Length;                                //获取当前文件大小  
                        listItem.SubItems.Add(Math.Ceiling(decimal.Divide(length, 1024)) + " KB");

                        //获取文件最后访问时间  
                        //listItem.SubItems.Add(fileInfo[i].LastWriteTime.ToString());  

                        //获取文件扩展名时可用Substring除去点 否则显示".txt文件"  
                        listItem.SubItems.Add(fileInfo[i].Extension + "文件");
                        //加载数据至listview  
                        this.listView1.Items.Add(listItem);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("选择的路径不能为盘根目录，且具有读写权限", "错误", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);

                }
                    //结束数据处理,UI界面一次性绘制 否则可能出现闪动情况  
                    this.listView1.EndUpdate();
            }


        }

        public void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            button3.Enabled = true;
           // ProgressBar1.Value = 0;
            //timer1.Enabled = false;
            ProgressBar1.Style = ProgressBarStyle.Blocks;
            start = false;
            timego = 0;
            button3.Text = "数据处理";
            textBox1.Enabled = true;
            //关闭LMTPro程序
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process myProcess in myProcesses)
            {
                if ("LMTPro" == myProcess.ProcessName)
                    myProcess.Kill();//强制关闭该程序
            }
        }

        private void timer1_Tick1(object sender, EventArgs e)
        {

            ProgressBar1.Value++;
            if(ProgressBar1.Value == 99)ProgressBar1.Value = 0;

        }
        public string getPath()
        {
            if (SelectPath == null || SelectPath.Trim().Length == 0)
                return "";
            else
                return SelectPath+"\\";
        }
        /*
        public string getFile1()
        {
            return file1;
        }
        public string getFile2()
        {
            return file2;
        }
        public void setFile1(string f)
        {
            file1 = f;
        }
        public void setFile2(string f)
        {
            file2= f;
        }*/
        private void 结果分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OutSet os = new OutSet(this);
            os.ShowDialog();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new About(this).ShowDialog();
        }


        private void 帮助文档ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult a = MessageBox.Show("请阅读软件使用说明书", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void button5_Click1(object sender, EventArgs e)
        {
            string tbTxt = textBox1.Text.Trim();
            if (Directory.Exists(tbTxt))
                userInputPath(tbTxt);
            else
                MessageBox.Show("文件目录不存在或者权限不允许操作", "错误", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);

        }
        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Control || e.KeyCode == Keys.Enter)
            {
                string tbTxt = textBox1.Text.Trim();
                if (Directory.Exists(tbTxt))
                    userInputPath(tbTxt);
                else{
                    textBox1.Text = "请输入目录或者在左侧选中目录";
                    MessageBox.Show("文件目录不存在或者权限不允许操作", "错误", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                
                }
               
            }
        }

        private void 配置信息修改ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {

            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {         
               System.Diagnostics.Process.Start("notepad.exe", filenameSiteInfo);
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }
        }

        private void 测点数据文件查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //相对路径
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            if (File.Exists(filenameSiteInfo))
            {
                ConfigInfo.ConfigInfo config = new ConfigInfo.ConfigInfo(SelectPath);

                config.selectpathconfig = SelectPath;
                config.ShowDialog();
            }
            else
            {
                MessageBox.Show("当前文件夹不存在SiteInfo.dat文件");
            }
        }

        private void 单点处理SSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mode = "SS"; changeMode();
        }

        private void 远参考处理RRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mode = "RR"; changeMode();
        }

        private void 磁场相ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mode = "RRHC"; changeMode();
        }

        private void 共用磁道处理UHToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mode = "UH"; changeMode();
        }
        private void changeMode()
        {
            ArrayList str = new ArrayList();
            string filenameSiteInfo = SelectPath + "\\" + "SiteInfo.dat";
            int index = 0;
            string line;
            if (File.Exists(filenameSiteInfo))
            {
                StreamReader sr = new StreamReader(filenameSiteInfo, System.Text.Encoding.Default);
                try
                {
                    index = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        str.Add(line);
                    }
                    sr.Close();
                }
                catch (Exception ex)
                {
                    sr.Close();
                    MessageBox.Show("配置文件错误#1"); 
                    return;
                }
            }
            if (str.Count < 12) { MessageBox.Show("SiteInfo.dat配置文件错误,请检查#2"); return; }
            if (mode == "SS") { 
                str[5] = "0";
                str[9] = "0";
                str[11] = "0";
            }
            else if (mode == "RR")
            {
                str[5] = "1";
                str[9] = "0";
                str[11] = "0";
            }
            else if (mode == "RRHC")
            {
                str[5] = "1";
                str[9] = "1";
                str[11] = "0";
            }
            else if (mode == "UH")
            {
                str[5] = "0";
                str[9] = "0";
                str[11] = "1";
            }

            StreamWriter sw = new StreamWriter(filenameSiteInfo, false, System.Text.Encoding.Default);
            index = 0;
            foreach (string s in str)
            {
                sw.WriteLine(s);
            }
            sw.Close();
        }
        private static System.Diagnostics.Process p;
        private void button5_Click(object sender, EventArgs e)
        {
            if (p == null)
            {
                p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "MTSHOAW.exe";
                p.Start();
            }
            else
            {
                if (p.HasExited) //是否正在运行
                {
                    p.Start();
                }
            }
            p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        } 
    }
}